//
//  ViewExtension.swift
//  RKTemplate
//
//  Created by rubick on 2021/3/22.
//

import UIKit
import Foundation

// MARK:  frame相关
extension UIView {
    // x
    var rk_x: CGFloat {
        get {
            return frame.origin.x
        }
        set(newValue) {
            var tempFrame: CGRect = frame
            tempFrame.origin.x = newValue
            frame = tempFrame
        }
    }
    // y
    var rk_y: CGFloat {
        get {
            return frame.origin.y
        }
        set(newValue) {
            var tempFrame: CGRect = frame
            tempFrame.origin.y = newValue
            frame = tempFrame
        }
    }
    // height
    var rk_height: CGFloat {
        get {
            return frame.size.height
        }
        set(newValue) {
            var tempFrame: CGRect = frame
            tempFrame.size.height = newValue
            frame = tempFrame
        }
    }
    // width
    var rk_width: CGFloat {
        get {
            return frame.size.width
        }
        set(newValue) {
            var tempFrame: CGRect = frame
            tempFrame.size.width = newValue
            frame = tempFrame
        }
    }
    // size
    var rk_size: CGSize {
        get { return frame.size }
        set(newValue) {
            var temp = frame
            temp.size = newValue
            frame = temp
        }
    }
    // centerX
    var rk_centerX: CGFloat {
        get { return center.x }
        set(newValue) {
            var temp = center
            temp.x = newValue
            center = temp
        }
    }
    // centerY
    var rk_centerY: CGFloat {
        get { return center.y }
        set(newValue) {
            var temp = center
            temp.y = newValue
            center = temp
        }
    }
    //
    var screenWidth: CGFloat {
        get {
            guard let window = self.window else {
                guard let window = UIWindow.rk_KeyWindow() else {
                    return 0
                }
                return window.frame.size.width
            }
            return window.frame.size.width
        }
    }
    var screenHeight: CGFloat {
        get {
            guard let window = self.window else {
                guard let window = UIWindow.rk_KeyWindow() else {
                    return 0
                }
                return window.frame.size.height
            }
            return window.frame.size.height
        }
    }
}
extension UIView {
    private struct AssociatedKeys {
        static var descriptiveName = "AssociatedKeys.DescriptiveName.blurView"
    }
    private (set) var blurView: BlurView {
        get {
            if let blurView = objc_getAssociatedObject(self, &AssociatedKeys.descriptiveName) as? BlurView {
                return blurView
            }
            self.blurView = BlurView(to: self)
            return self.blurView
        }
        set(blurView) {
            objc_setAssociatedObject(self, &AssociatedKeys.descriptiveName, blurView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    class BlurView {
        private var superview: UIView
        private var blur: UIVisualEffectView?
        private var editing: Bool = false
        private (set) var blurContentView: UIView?
        private (set) var vibrancyContentView: UIView?
        var animationDuration: TimeInterval = 0.1
        var style: UIBlurEffect.Style = .light {
            didSet {
                guard oldValue != style, !editing else { return }
                applyBlurEffect()
            }
        }
        var alpha: CGFloat = 0 {
            didSet {
                guard !editing else { return }
                if blur == nil {
                    applyBlurEffect()
                }
                let alpha = self.alpha
                UIView.animate(withDuration: animationDuration) {
                    self.blur?.alpha = alpha
                }
            }
        }
        init(to view:UIView) {
            self.superview = view
        }
        func setup(style: UIBlurEffect.Style, aplpha: CGFloat) -> Self {
            self.editing = true
            self.style = style
            self.alpha = alpha
            self.editing = false
            return self
        }
        func enable(isHidden: Bool = false) {
            if blur == nil {
                applyBlurEffect()
            }
            self.blur?.isHidden = isHidden
        }
        private func applyBlurEffect() {
            blur?.removeFromSuperview()
            applyBlurEffect(style: style, blurAlpha: alpha)
        }
        private func applyBlurEffect(style: UIBlurEffect.Style, blurAlpha: CGFloat) {
            superview.backgroundColor = UIColor.clear
            let blurEffect = UIBlurEffect(style: style)
            let blurEffectView = UIVisualEffectView(effect: blurEffect)
            let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
            let vibrancyView = UIVisualEffectView(effect: vibrancyEffect)
            blurEffectView.contentView.addSubview(vibrancyView)
            blurEffectView.alpha = blurAlpha
            superview.insertSubview(blurEffectView, at: 0)
            blurEffectView.addAlignedConstrains()
            vibrancyView.addAlignedConstrains()
            self.blur = blurEffectView
            self.blurContentView = blurEffectView.contentView
            self.vibrancyContentView = vibrancyView.contentView
        }
    }

    private func addAlignedConstrains() {
        translatesAutoresizingMaskIntoConstraints = false
        addAlignConstraintToSuperview(attribute: .top)
        addAlignConstraintToSuperview(attribute: .leading)
        addAlignConstraintToSuperview(attribute: .trailing)
        addAlignConstraintToSuperview(attribute: .bottom)
    }
    private func addAlignConstraintToSuperview(attribute: NSLayoutConstraint.Attribute) {
        superview?.addConstraint(
            NSLayoutConstraint(item: self, attribute: attribute, relatedBy: NSLayoutConstraint.Relation.equal, toItem: superview, attribute: attribute, multiplier: 1, constant: 0)
        )
    }
    // 裁剪View圆角
    func clipRestCorner(direction: UIRectCorner, cornerRadius: CGFloat) {
        let cornerSize = CGSize(width: cornerRadius, height: cornerRadius)
        let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: direction, cornerRadii: cornerSize)
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.path = maskPath.cgPath
        layer.addSublayer(maskLayer)
        layer.mask = maskLayer
    }
}
private let durationFadeAnimation:TimeInterval = 0.2
extension UIView {
    func animateFadeIn(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: durationFadeAnimation, delay: 0, options: [.beginFromCurrentState], animations: {
            self.alpha = 1
        }, completion: { _ in
            completion?()
        })
    }
    func animateFadeOut(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: durationFadeAnimation, delay: 0, options: [.beginFromCurrentState], animations: {
            self.alpha = 0
        }, completion: { _ in
            completion?()
        })
    }
    static func animateFadeOut(_ views: [UIView?], completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: durationFadeAnimation, animations: {
            views.forEach { $0?.alpha = 0 }
        }, completion: { _ in
            completion?()
        })
    }
    static func animateFadeIn(_ views: [UIView?], completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: durationFadeAnimation, animations: {
            views.forEach { $0?.alpha = 1 }
        }, completion: { _ in
            completion?()
        })
    }
}
